package com.diqye.engine.interceptor.validator;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Iterator;

import org.apache.commons.io.IOUtils;

import com.diqye.db.model.XModel;
import com.diqye.engine.Constant;
import com.diqye.engine.Controller;
import com.diqye.engine.interceptor.Interceptor;
import com.diqye.templet.util.Strings;
import com.google.gson.Gson;
/**
 * validJson
 * {field1:{require:true,maxl:100,minl:1}} 必填 最大长度 最小长度
 * @author qinzl
 *
 */
public class SimpleValidator extends Interceptor {

	public  XModel validators;
	public SimpleValidator(InputStream istream){
		try {
			validators = new Gson().fromJson(IOUtils.toString(istream, Constant.encoding), XModel.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public boolean validateAction(String action) {
		return validators.containsKey(action);
	}

	@Override
	protected void intercept(String action,Controller controller,Method method,Interceptor last) throws Exception {
		XModel valid = validators.getModel(action);
		Iterator<String> ite = valid.keySet().iterator();
		XModel reqModel = controller.getReqModel().getModel("params");
		while(ite.hasNext()){
			String field = ite.next();
			XModel validDetail = valid.getModel(field);
			String reqFieldValue = reqModel.gts(field);
			String errMsg = check(reqFieldValue,validDetail,validDetail.getToStr("name"));
			if( errMsg!= null){
				controller.renderErr(errMsg);
				return;
			}
		}
		next.intercept(action,controller,method);

	}
	
	private String check(String value,XModel validDetail,String field){
		if(value==null){
			value = "";
		}else{
			value = value.trim();
		}
		//验证非空
		Object v = validDetail.get("require");
		if(v != null&&((Boolean)v).booleanValue()){
			if(value.equals("")){
				return Strings.format("{0}为必填项", field);
			}
		}
		v = validDetail.getInt("min");
		if(v!=null&&!"".equals(value)){
			int minl = (Integer)v;
			if(value.length()<minl){
				return Strings.format("{0}最小长度为{1},实际长度为{2}", field,minl,value.length());
			}
		}
		v = validDetail.getInt("max");
		if(v!=null&&!"".equals(value)){
			int maxl = (Integer)v;
			if(value.length()>maxl){
				return Strings.format("{0}最大长度为{1},实际长度为{2}", field,maxl,value.length());
			}
		}
		String v4 = validDetail.gts("reg");
		if(v4!=null&&!"".equals(value)){
			if(!value.matches(v4)){
				return Strings.format(validDetail.gts("regtip"),field);
			}
		}
		return null;
	}

	

}
